﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using PropertyManagement.Core;
using PropertyManagement.Modal;
namespace PropertyManagement {
    public partial class Login : Form {
        SystemUserManage SystemUserManage { get; set; }
        public Login( ) {
            InitializeComponent( );
            SystemUserManage = new SystemUserManage();
        }

        private void button1_Click(object sender, EventArgs e) {
            innerLogin(sender);
        }

        private void innerLogin(object sender) {
            var username = tb_UserName.Text.Trim();
            var pwd = tb_Pwd.Text.Trim().ToLower();
            this.Loading("正在登录", sender);
            if (CheckUserAndPwd(username, pwd)) {
                var loginStatus = SystemUserManage.Login(username, pwd);
                this.Loaded(sender);
                if (loginStatus == LoginStatus.InvalidPassword) {
                    ShowErrorMsg("密码错误");
                    tb_Pwd.Text = "";
                    tb_Pwd.Focus();
                }
                else if (loginStatus == LoginStatus.NoUser) {
                    ShowErrorMsg("该用户不存在");
                    tb_Pwd.Text = "";
                    tb_UserName.Text = "";
                    tb_UserName.Focus();
                }
                else {
                    OpenMainForm(username, pwd);
                }
            }
            else {
                this.Loaded(sender);
                ShowErrorMsg("输入错误,用户名和密码不能为空");
                tb_Pwd.Text = "";
                tb_UserName.Text = "";
                tb_UserName.Focus();
            }
        }


        private void OpenMainForm( string username,string password) {
            (new MainForm(username,password)).Show();
            this.Hide();
        }

        private void ShowErrorMsg(string p) {
            FormHelper.ShowErrorMsg(p);
        }

        private bool CheckUserAndPwd(string username, string pwd) {
            return !string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(pwd);
        }

        private void button2_Click(object sender, EventArgs e) {
            if (MessageBox.Show("是否关闭物业管理系统？", "提示", MessageBoxButtons.YesNo,
                                MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.Yes) {
                Application.Exit();
            }
            
        }

        private void Login_Load(object sender, EventArgs e) {
            GlobalSetting.LoginForm = this;
            GlobalSetting.IsChangeUser = false;
            if (SettingHelper.HasDBSetFile) {
                groupBox2.Hide( );
                this.Height = 212;

            } else {
                MessageBox.Show("第一次使用，请设置数据库配置");
            }
#if DEBUG
            tb_UserName.Text = "admin";
            tb_Pwd.Text = "12345678";
#endif 
        }

        private void button3_Click(object sender, EventArgs e) {
            ShowOrHideConfigPanel();
        }

        private void ShowOrHideConfigPanel() {
            if (this.Height == 212) {
                tb_UserName.Enabled = tb_Pwd.Enabled = false;
                groupBox2.Show();
                this.Height = 413;
            }
            else {
                tb_UserName.Enabled = tb_Pwd.Enabled = true;
                groupBox2.Hide();
                this.Height = 212;
            }
        }

        private void button4_Click(object sender, EventArgs e) {
            try {
                if (textBox2.Text.Trim( ) == "") {
                    MessageBox.Show("请输入数据库名称");
                    textBox2.Focus( );
                } else if (textBox1.Text.Trim( ) == "") {
                    MessageBox.Show("请输入服务器名称");
                    textBox1.Focus( );
                } else {
                    
                    SetDBSetting(textBox1.Text.Trim( ), textBox2.Text.Trim( ), null, null);
                    CheckDBConnectionAndInit();
                    ShowOrHideConfigPanel();
                }
            } catch {
               ShowErrorMsg("配置文件异常");
            }
        }



        private void SetDBSetting(string server, string db, string name, string password) {
            var connStr = "Server =" + server + ";Database =" + db;
            if (name != null) {
                connStr += ";User ID=" + name + ";Password=" + password;
            } else {
                connStr += ";Integrated Security=True;";
            }
            connStr += ";Trusted_Connection = False;";
            SettingHelper.WriteDBConnectionSetting(connStr);
            SqlServerHelper.ConnectionString = connStr;
        }

        private void button7_Click(object sender, EventArgs e) {
            try {
                if (textBox3.Text.Trim( ) == "") {
                    MessageBox.Show("请输入数据库名称");
                    textBox3.Focus( );
                } else if (textBox4.Text.Trim( ) == "") {
                    MessageBox.Show("请输入服务器名称");
                    textBox4.Focus( );
                } else {
                    this.Height = 200;
                    SetDBSetting(textBox4.Text.Trim( ), textBox3.Text.Trim( ), textBox5.Text.Trim( ), textBox6.Text.Trim( ));
                    CheckDBConnectionAndInit();
                    ShowOrHideConfigPanel( );
                }
            } catch {
                ShowErrorMsg("配置文件异常");
            }
        }

        private bool CheckDBConnectionAndInit( ) {
            try {
                var userM = new SystemUserManage();
                if (!userM.IsExisted("admin")) {
                    userM.Add("admin","12345678",RightLevel.Administrator);
                    
                }
                return true;
            }
            catch (Exception e) {
                
                ShowErrorMsg("数据库连接失败，请检查配置");
                
            }
            return false;
        }

        private void tb_Pwd_KeyPress(object sender, KeyPressEventArgs e) {
          if (e.KeyChar == '\r') {
              innerLogin(button1);
          }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if(string.IsNullOrWhiteSpace(tb_UserName.Text.Trim())){
                FormHelper.ShowErrorMsg("请先输入您的用户名");
                return;
            }
            (new FindbackPassword(tb_UserName.Text.Trim())).ShowDialog(this);
        }
        

    }
}
